import { shell, BrowserWindow, BrowserWindowConstructorOptions } from 'electron'
import { join } from 'path'
import { is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'

export type CreateBrowserWindowType = {
  url: string
  options?: BrowserWindowConstructorOptions
}

export const createBrowserWindow = (options: CreateBrowserWindowType): BrowserWindow => {
  const windiw = new BrowserWindow({
    show: false,
    frame: false,
    resizable: false,
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    },
    ...options.options
  })
  windiw.menuBarVisible = false

  windiw.on('ready-to-show', () => {
    windiw.show()
  })

  windiw.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    windiw.loadURL(process.env['ELECTRON_RENDERER_URL'] + options.url)
  } else {
    windiw.loadFile(join(__dirname, '../renderer/index.html'), {
      hash: options.url
    })
  }
  return windiw
}
